package tablet.client.workspace;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import tablet.client.workspace.R;
import websocket4j.client.WebSocket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class CommunicationActivity extends Activity{
	
	private static TextView infoTv;
	private static TextView infoTv2;
	private static ImageButton channelPlusButton;
	private static ImageButton channelMinusButton;
	private static Handler handler;
	private CommunicationThread communicationThread;
	private static WebSocket ws;
	private static boolean steelAlive;
	private static Tv currentTv;
	private static ArrayList<String> urls;
	private static String ip;
	private static Integer port;
	private SteelAliveThread sAlive;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.communication);
  
        // Create a handler to update the UI
		handler = new Handler();
		
		//Getting IP and Port
        Bundle commBundle = this.getIntent().getExtras();
        ip = commBundle.getString("ip");
        Log.i("ipCommunication", ip);
        String stPort = commBundle.getString("port");
        Log.i("portCommunication", stPort);
        port = Integer.valueOf(stPort);
		
        //TextView
        infoTv = (TextView) findViewById(R.id.textView2);
        infoTv.setText("@"+ip+":"+port+"\n---------------------------------------------" );
        infoTv2 = (TextView) findViewById(R.id.textData);
        infoTv2.setMovementMethod(new ScrollingMovementMethod());
        
        //Buttons
        channelPlusButton = (ImageButton) findViewById(R.id.channelPlus);
        channelPlusButton.setOnClickListener(new View.OnClickListener() {
        	@Override
            public void onClick(View v) {
        		Runnable runPlusChannel = new Runnable() {
        			@Override
        			public void run(){
        				if(currentTv!=null){
        					try {
        						ws.sendMessage(Constants.PLUS_CHANNEL);
        					} catch (IOException e) {
        						// TODO Auto-generated catch block
        						e.printStackTrace();
        					}
        				}        				
        			}
        		};
        		Thread plusChannelThread = new Thread(runPlusChannel);
        		plusChannelThread.start();
            }
        });
        channelMinusButton = (ImageButton) findViewById(R.id.channelMinus);
        channelMinusButton.setOnClickListener(new View.OnClickListener() {
        	@Override
            public void onClick(View v) {
        		Runnable runMinusChannel = new Runnable() {
        			@Override
        			public void run(){
        				if(currentTv!=null){
        					try {
        						ws.sendMessage(Constants.MINUS_CHANNEL);
        					} catch (IOException e) {
        						// TODO Auto-generated catch block
        						e.printStackTrace();
        					}
        				}        				
        			}
        		};
        		Thread minusChannelThread = new Thread(runMinusChannel);
        		minusChannelThread.start();
            }
        });
              
		communicationThread = new CommunicationThread();
		communicationThread.start();
		
		
		sAlive = new SteelAliveThread();
		sAlive.start();	
		
    }
		
	static public class CommunicationThread extends Thread {
		Tv tvAux = null;
		@Override
		public void run() {
			 try {
				ws = new WebSocket(ip, port, "");
				ws.sendMessage("GET");
				currentTv= new Tv(new JSONObject(ws.getMessage()));
				if(currentTv != null){
					steelAlive = true;
					urls = new ArrayList<String>(Constants.MAX_DATA);
					urls.add(currentTv.getWebSite());
					handler.post(new MyRunnable());
				}
				while(steelAlive){
					tvAux= new Tv(new JSONObject(ws.getMessage()));
					
					if((tvAux!=null)&&(!tvAux.equals(currentTv))){
						currentTv = tvAux;
						urls.add(currentTv.getWebSite());
						handler.post(new MyRunnable());
					}
				}
				ws.close();
			} catch (IOException e) {
				steelAlive = false;
				e.printStackTrace();
			} catch (JSONException e) {
				steelAlive = false;
				e.printStackTrace();
			}
		}
	}
	
	public void plusChannel(View view){
		if(currentTv!=null){
			try {
				ws.sendMessage(Constants.PLUS_CHANNEL);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
    public void minusChannel(View view) {
		if(currentTv!=null){
			try {
				ws.sendMessage(Constants.MINUS_CHANNEL);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	

		
	static public class MyRunnable implements Runnable {
		public void run() {
			String urlAux = null; 
			String old = infoTv2.getText().toString();
			infoTv2.setText(currentTv.toString()+"\n----------" +
					"-----------------------------------\n"+old);
			for(int i = 0; i<urls.size();i++){
				urlAux = urls.get(i);
				Pattern pattern = Pattern.compile(urlAux);
				Linkify.addLinks(infoTv2, pattern, "");				
			}
		}
	}	
	
	static public class SteelAliveThread extends Thread {
		@Override
		public void run() {
			while(steelAlive){
				try {
					ws.sendMessage("ALIVE");
					Thread.sleep(60000); // repeat every 1 min.
				} catch (InterruptedException e) {
					steelAlive = false;
				} catch (IOException e) {
					steelAlive = false;
				}
			}
		}
	}
	
}


